#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>

#define LED_OFF _IOW('l',0,int)
#define LED_ON _IOW('l',1,int)
#define LED_READ _IOWR('l',2,int)

int main(int argc, const char** argv)
{
    int request;
    if(argc != 3)
    {
        printf("usage: %s <on/off> <1/2/3>\n",argv[0]);
        return -1;
    }

    int fd = open("/dev/leds", O_RDWR);
    if(fd < 0)
    {
        perror("open /dev/leds is failed");
        return -1;
    }

    if(strcmp(argv[1], "on") == 0){
        request = LED_ON;
    }else if(strcmp(argv[1], "off") == 0){
        request = LED_OFF;
    }else{
        printf("usage: %s <on/off> <1/2/3>\n",argv[0]);
        close(fd);
        return -1;
    }

    int ledIndex = strtoul(argv[2], NULL, 0);
    if(ledIndex > 3 || ledIndex < 1)
    {
        printf("usage: %s <on/off> <1/2/3>\n",argv[0]);
        close(fd);
        return -1;
    }
    ioctl(fd, request, &ledIndex);
    ioctl(fd, LED_READ, &ledIndex);
    printf("led%s is %s\n", argv[2], ledIndex?"on":"off");
    close(fd);

    return 0;
}